<template>
	<view>
		<view class="padding">
			<view class="box padding-lg bg-white radius-xl">
				<view class="item crow margin-bottom-xl">
					<view class="left text-left">联系地址</view>
					<view class="right">
					  <view v-if="form.address_name">
              {{ form.address_name}}
            </view>
            <div>
              {{ form.address}}
            </div>
					</view>
					<view class="cuIcon-locationfill locationfill" @click="choseLocation"></view>
				</view>
				<view class="item crow margin-bottom-xl">
					<view class="left text-left">门牌号</view>
					<view class="right">
						<input type="text" placeholder="门牌号,例如[1栋101室]" v-model="form.code">
					</view>
				</view>
				<view class="item crow margin-bottom-xl">
					<view class="left text-left">联系人</view>
					<view class="right">
						<input type="text" placeholder="请输入联系人" v-model="form.nickname">
					</view>
				</view>
				<view class="item crow margin-bottom-xl">
					<view class="left text-left">联系电话</view>
					<view class="right">
						<input 
							type="number" 
							placeholder="请输入联系电话" 
							v-model="form.phone"
							maxlength="11">
					</view>
				</view>

				<view class="item crow">
					<view class="left text-left">设为默认</view>
					<view class="right">
						<input type="text" disabled="">
					</view>
					<u-switch
						:value="selectedOption"
						@change="setDefault"
						:activeValue="1"
						:inactiveValue="0"
						activeColor="#0ab27d"
						style="transform: scale(0.7);">
					</u-switch>
				</view>
			</view>

			<view class="padding margin-top-lg">
				<view class="flex flex-direction">
					<button class="cu-btn china-btn-bg lg round" @click="submit()">保存</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import QQMapWX from '@/sdk/qqmap-wx-jssdk.js';
	export default {
		data() {
			return {
				pageType:'add',
				selectedOption:1,
				form: {
          address:'',
          address_name: '',
          code:'',
          nickname:'',
          phone:'',
          is_default:1,
          longitude:'114.96681',
          latitude:'27.091243',
          id: undefined
        },
			};
		},

		onLoad(options) {
      let that = this;
			this.pageType = options.pageType;
      if (options.pageType == 'edit' && options.addressId) {
        uni.showLoading({
          title: '加载中',
          mask: true,
          duration: 0
        });
        this.$http.getAddressDetail({ id: options.addressId }).then(res => {
          this.form = res
          this.selectedOption = res.is_default
          console.log(this.form)
        }).finally(() => {
          uni.hideLoading();
        });
      } else {
        uni.getLocation({
          type: 'wgs84',
          success: function(res) {
            uni.hideLoading();
            console.log(res)
            that.form.longitude = res.longitude
            that.form.latitude = res.latitude
            that.getName({
              longitude: res.longitude,
              latitude: res.latitude
            })
          },
          fail: function(err) {
            uni.hideLoading();
            console.log(err)
          },
          complete(res) {
            uni.hideLoading();
          }
        });
      }
		},
		methods:{
      		// 手机号格式校验
      validatePhone(phone) {
        // 中国大陆手机号正则表达式
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone);
      },
      
      getName(e) {
        let that = this
        var qqmapsdk = new QQMapWX({
          key: 'AE3BZ-SVQKU-BHUVT-GNGMH-QVJKK-2PFRJ' // 必填
        });
        qqmapsdk.reverseGeocoder({
          //Object格式
          location: {
            latitude: e.latitude,
            longitude: e.longitude
          },
          success: function (res) {
            console.log(res)
            that.form.address = res.result.address
            that.form.address_name = res.result.formatted_addresses.recommend
          }, fail: function (error) {
            console.error(error);
          },
          complete: function (res) {
            //console.log(res);
          }
        })
      },

			submit(){
				let form = {
          id: this.form.id,
          address: this.form.address,
          address_name: this.form.address_name,
          code: this.form.code,
          nickname: this.form.nickname,
          phone: this.form.phone,
          longitude: this.form.longitude,
          latitude: this.form.latitude,
          member_id: uni.getStorageSync('userInfo').id
        };
				form.is_default = this.selectedOption;
        if (!form.address) {
          uni.showToast({
            title: '请选择地址',
            icon: 'none'
          })
          return;
        }
        if (!form.nickname) {
          uni.showToast({
            title: '请输入联系人',
            icon: 'none'
          })
          return;
        }
        if (!form.phone) {
          uni.showToast({
            title: '请输入联系电话',
            icon: 'none'
          })
          return;
        }
        if (!this.validatePhone(form.phone)) {
          uni.showToast({
            title: '请输入正确的手机号格式',
            icon: 'none'
          })
          return;
        }
        if (form.id) {
          this.$http.updateAddress(form).then(() => {
            uni.showToast({
              title: '编辑成功',
              icon: 'success',
              duration: 2000
            });
            uni.navigateBack();
          });
        } else {
          this.$http.createAddress(form).then(() => {
            uni.showToast({
              title: '新增成功',
              icon: 'success',
              duration: 2000
            });
            uni.navigateBack();
          });
        }
			},
			setDefault(e){
				let selectedOption = this.selectedOption == 0?1:0;
				this.selectedOption = selectedOption;
			},
      choseLocation() {
        console.log('----')
        wx.chooseLocation({
          latitude: this.form.latitude,
          longitude: this.form.longitude,
          address: this.form.address,
          name: this.form.address_name,
          success: res => {
            if (res.errMsg === 'chooseLocation:ok') {
              console.log(res)
              if (!res.address) {
                uni.showToast({
                  title: '请选择正常地址',
                  icon: 'none'
                })
                return;
              }
              this.form.longitude = res.longitude;
              this.form.latitude = res.latitude;
              this.form.address = res.address;
              this.form.address_name = res.name;
            } else {
              uni.showToast({
                title: '获取位置失败',
                icon: 'none'
              })
            }
          },
          fail: err => {
            console.log(err);
          },
          complete: (err) => {
            console.log(err);
          }
        });
      }
		}
	}
</script>

<style lang="less" scoped>
.box{
	.item{
		width: 100%;
		.left{
			width: 25%;
		}
		.right{
			width: 69%;
			input{
				font-size: 26upx;
			}
		}
		.locationfill{
			font-size: 35upx;
		}
	}
	

}
</style>
